<template>
  <div>
    <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="likeName" class="input" @keydown.enter.native="search">
    </el-input>
    <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
    <el-button type="primary" @click="dialog=true">新增</el-button>
    <el-table :data="userData" style="width:100%">
      <el-table-column prop="account" label="账号"></el-table-column>
      <el-table-column prop="name" label="姓名">
        <template slot-scope="scope">
          <el-tag>{{scope.row.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template slot-scope="scope">
          <el-tag>{{scope.row.create_time|formatDate}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">
          <el-tag type="danger">{{sexName[scope.row.sex]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="送货地址"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="changeUpdateDrawer(scope.row)">编辑</el-button>
          <el-button type="text" @click="delUser(scope.row.user_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="changeMaxSize" @current-change="changePageSize" :current-page="currentPage"
      :page-sizes="pageSizes" :page-size="pageSize" layout="total,sizes,prev,pager,next,jumper" :total="total"></el-pagination>
    <!--抽屉-->
    <el-drawer title="新增用户" :before-close="cancel" :visible.sync="dialog" direction="ltr" custom-class="demo-drawer"
      ref="addDrawer" size="50%">
      <!--表单组件-->
      <div class="form-contaniner">
        <el-form label-position="left" :model="user" :rules="rules" ref="addUser">
          <el-form-item label="账号" prop="account">
            <el-input v-model="user.account"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="user.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="user.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="user.sex">
              <el-radio :label="0">保密</el-radio>
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item prop="address">
          <el-form-item label="收货地址">
            <el-input v-model="user.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button>取消</el-button>
            <el-button type="primary" @click="addUser('addUser')">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

      <!--修改抽屉-->
    <el-drawer title="修改用户" :before-close="cancel" :visible.sync="updateDialog" direction="rtl" custom-class="demo-drawer"
      ref="updateDrawer" size="50%">
      <!--表单组件-->
      <div class="form-contaniner">
        <el-form label-position="left" :model="user" :rules="rules" ref="updateUser">
          <el-form-item label="账号" prop="account">
            <el-input v-model.lazy="user.account"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model.lazy="user.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model.lazy="user.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.lazy="user.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model.lazy="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model.lazy="user.sex">
              <el-radio :label="0">保密</el-radio>
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item prop="address">
          <el-form-item label="收货地址">
            <el-input v-model="user.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateUser('updateUser')">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'
  export default {
    name:"index1",
    data() {
      return {
        userData: [],
        currentPage: 1,
        pageSizes: [10, 100, 200, 500, 1000],
        pageSize: 10,
        total: 400,
        sexName: ["保密", "男", "女"],
        likeName: "",
        dialog: false,
        user: {
          account: "",
          password: "",
          name: "",
          email: "",
          phone: "",
          sex: 0,
          address: ""
        },
        rules: {
          account: [{
            required: true,
            message: "用户的账号不能为空",
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: "用户的密码不能为空",
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: "用户的姓名不能为空",
            trigger: 'blur'
          }],
          email: [{
            type: "email",
            message: "用户邮箱格式不正确",
            trigger: "change"
          }, {
            required: true,
            message: "用户邮箱不能为空",
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: "用户的手机号不能为空",
            trigger: 'blur'
          }],
          address: [{
            required: true,
            message: "用户的收货地址不能为空",
            trigger: 'blur'
          }]
        },
        updateDialog:false
      }

    },
    components: {

    },
    methods: {
      //改变一页容纳的总条数
      changeMaxSize(maxSize) {
        //默认接收到总条数，但是我需要总条数和当前页吗
        let currentPage = this.currentPage
        let likeName = this.likeName
        this.getUserData(currentPage, maxSize, likeName)
      },
      //改变页码时
      changePageSize(currentPage) {
        //默认接收的是改变的页码，但是我需要总条数和当前页码
        let maxSize = this.pageSize
        let likeName = this.likeName
        this.getUserData(currentPage, maxSize, likeName)
      },
      getUserData(page, maxSize, likeName) {
        let params = {
          page,
          maxSize
        }
        if (likeName != null && likeName != "") {
          params['likeName'] = likeName
        }
        //发送get请求
        axios.get("http://chenxueli.site:8081/ssm/selectPageUserList", {
            params
          })
          .then((res) => {
            console.log(res)
            if (res.data.resultCode == 0) {
              //将获取到的真实数据复给变量
              let data = res.data.data
              //将列表数据复制到data的userData属性中
              this.userData = data.list
              //当前页码
              this.currentPage = data.pageNum
              //一页显示的总条数
              this.pageSize = data.pageSize
              //总条数
              this.total = data.total
            } else {
              alert(res.data.message)
            }
          })
      },
      //搜索
      search() {

        let likeName = this.likeName
        let pageSize = this.pageSize
        this.getUserData(1, pageSize, likeName)
      },
      //删除
      delUser(userId) {
        let params = {
          userId
        }

        this.$confirm("此操作将永久删除该记录", "是否继续", {
          confirmButtonText: "残忍丢弃",
          cancelButtonText: "容我再想想",
          type: "warning"
        }).then(() => {
          //点击确认
          //将payload参数转化成formData
          params = qs.stringify(params);
          axios.post("http://chenxueli.site:8081/ssm/deleteUser", params)
            .then((res) => {
              if (res.data.resultCode === 0) {
                this.$message({
                  type: "success",
                  message: res.data.message
                })

                let page = this.currentPage
                let maxSize = this.pageSize
                let likeName = this.likeName
                this.getUserData(page, maxSize, likeName)
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                })
              }
            })


        }).catch(() => {
          //点击取消
        });
      },
      //关闭抽屉
      cancel(done) {
        //先将表格的数据清除
        this.user={
          account: "",
          password: "",
          name: "",
          email: "",
          phone: "",
          sex: 0,
          address: ""
        }
        done();
      },
      //添加用户
      addUser(refName) {
        //校验
        this.$refs[refName].validate((valid) => {
          if (valid) {
            //校验成功！需要发送请求给服务器进行新增
            let params = this.user;
            params = qs.stringify(params);
            axios.post("http://chenxueli.site:8081/ssm/addUser", params).then((res)=>{
                if(res.data.resultCode===0){
                  //给出新增成功的提示
                    this.$message({
                        type:"success",
                        message:res.data.message
                    })
                    //抽屉内的内容全部清空
                       this.$refs[refName].resetFields()
                    //关闭抽屉
                    this.dialog=false
                    //获取第一页的数据
                   this.getUserData(1,10,null)
                }else{
                    //新增失败的提示
                    this.$message({
                        type:"error",
                        message:res.data.message
                    })
                }
            })
          } else {
            return false;
          }

        })
      },
      //切换修改抽屉，将数据回显到抽屉中
      changeUpdateDrawer(user){
          //将获取到的旧数据复制给data中
            this.user=user
            //打开修改抽屉
            this.updateDialog=true
      },
      //修改用户
      updateUser(refName){
        this.$refs[refName].validate((valid)=>{
            if(valid){
              let user=this.user;
                const param = (({user_id,account,password,name,head_img_url,address,email,phone,sex,version}) => ({user_id,account,password,name,head_img_url,address,email,phone,sex,version}))(user)
                 let params=qs.stringify(param);
                 axios.post("http://chenxueli.site:8081/ssm/updateUser", params).then((res)=>{
                     if(res.data.resultCode===0){
                       //给出修改成功的提示
                         this.$message({
                             type:"success",
                             message:res.data.message
                         })
                         //抽屉内的内容全部清空
                            this.$refs[refName].resetFields()
                         //关闭抽屉
                         this.updateDialog=false
                         //获取当前页的数据

                        this.getUserData(this.currentPage,this.pageSize,this.likeName)
                     }else{
                         //修改失败的提示
                         this.$message({
                             type:"error",
                             message:res.data.message
                         })
                     }
                 })
            }else{
                return false
            }
        })
      }
    },
    mounted() {
      this.getUserData(1, 10, null)
    },
    //过滤器
    filters: {
      formatDate(date) {
        return new Date(date).toLocaleString().replace(/:\d{1,2}$/, ' ');
      }
    }
  }
</script>

<style>
  .input {
    width: 180px;
  }

  .form-contaniner {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
  }
</style>
